﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Reflection;
using System.Web;
using System.Web.Compilation;
using System.Web.Http;
using System.Web.Mvc;
using System.Web.Optimization;
using System.Web.Routing;
using Autofac;
using Autofac.Integration.Mvc;
using Autofac.Integration.WebApi;
using DayDayUp.Core;
using DayDayUp.Core.Data;
using DayDayUp.Data;
using DayDayUp.Service.Posts;

namespace DayDayUp
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            var container = BuildContianer();
            EngineContext.Initialize(false, container);
           // log4net.Config.XmlConfigurator.Configure();

            AreaRegistration.RegisterAllAreas();
            GlobalConfiguration.Configure(WebApiConfig.Register);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }

        private IContainer BuildContianer()
        {
            var builder = new ContainerBuilder();


            //db
            builder.RegisterGeneric(typeof(MongoRepository<>)).As(typeof(IMongoRepository<>)).InstancePerHttpRequest();



            builder.RegisterType<WebWorkContext>().As<IWorkContext>().InstancePerHttpRequest();
            builder.RegisterType<PostService>().As<IPostService>().InstancePerHttpRequest();
          

       
            //controller
            var callingAssembly = Assembly.GetCallingAssembly();
            var referenceAssemly = BuildManager.GetReferencedAssemblies();

            //regist plugins controller
            //foreach (Assembly assembly in referenceAssemly)
            //{
            //    //var assemly = Assembly.Load(assemblyName); 
            //    builder.RegisterControllers(assembly);
            //    builder.RegisterApiControllers(assembly);


            //    //RegistReferenceAssembly(builder, assembly);
            //}
            builder.RegisterControllers(callingAssembly);
            builder.RegisterApiControllers(callingAssembly);



            var container = builder.Build();
            var resolver = new Autofac.Integration.Mvc.AutofacDependencyResolver(container);
            DependencyResolver.SetResolver(resolver);
            GlobalConfiguration.Configuration.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            return container;
        }
    }
}
